//
//  WMEFindContentViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/2/25.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEFindContentViewController.h"
#import "WMELayout.h"
#import "WMEFirstPageCollectionViewCell.h"
#import "WMEFirstPageModel.h"
#import <AFNetworking.h>
#import <MJRefresh.h>
#import "WMEFirstPageInformationVC.h"
#import "WMEFindCollectionHeadView.h"
@interface WMEFindContentViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, WMELayoutItemHeightDelegate>
@property (nonatomic, retain)UICollectionView *collectionView;/**<主视图*/
@property (nonatomic, retain)NSMutableArray *dataArr;/**<数据数组*/
@property (nonatomic, copy)NSString *urlStr;/**<网络请求的网址*/
@property (nonatomic, retain)NSNumber *nextStart;/**<下次请求起始位置*/
@end

@implementation WMEFindContentViewController
- (void)dealloc
{
    [_collectionView release];
    [_dataArr release];
    [_urlStr release];
    [_nextStart release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"详情";
    [self createView];
    [self data];
    //上拉加载
}
#pragma mark - 创建视图
- (void)createView
{
    //自定义layout
    WMELayout *layout = [[WMELayout alloc] init];
    //layout的count为2 两列
    layout.columCount = 2;
    //layout 的 列间距
    layout.columSparce = 10;
    //layout 的 行间距
    layout.rowSparce = 10;
    //layout的边距
    layout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    
    
    //初始化 collection
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:layout];
    //    [layout release];
    //设置collection的背景颜色
    _collectionView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    //签协议
    layout.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    [self.view addSubview:_collectionView];
//    _collectionView.contentInset = UIEdgeInsetsMake(150, 0, 0, 0);
    
    [layout release];
    [_collectionView release];

}
#pragma mark-数据处理
- (void)data
{
    NSString *url = @"http://www.duitang.com/napi/blog/list/by_category/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&filter_params=%7B%22price%22%3A%22%5B*+TO+100%5D%22%7D&path=&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522847630%2522%257D&screen_width=720&screen_height=1280&app_version=68&start=0&platform_name=Android&locale=zh&app_code=nayutas&cate_key=556eb6313b0d31b17a1c6ba4";
    self.urlStr = [url stringByReplacingOccurrencesOfString:@"cate_key=556eb6313b0d31b17a1c6ba4" withString:[NSString stringWithFormat:@"cate_key=%@", _interface]];
    //AFN网络请求
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:_urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSArray *arr = responseObject[@"data"][@"object_list"];
        self.nextStart = responseObject[@"data"][@"next_start"];
        self.dataArr = [WMEFirstPageModel modelHandlerWithArray:arr];
        if (_dataArr.count == 0) {
            UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
            label.text = @"内容为空";
            label.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:label];
        }else {
            [self loadingFunction];
            [_collectionView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
}
#pragma mark -collection的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView registerClass:[WMEFirstPageCollectionViewCell class] forCellWithReuseIdentifier:@"findContentCell"];
    WMEFirstPageCollectionViewCell *findContentCell = [_collectionView dequeueReusableCellWithReuseIdentifier:@"findContentCell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        WMEFirstPageModel *model = _dataArr[indexPath.row];
        findContentCell.model = model;
    }
    return findContentCell;
}
#pragma mark - cell的高度 
- (CGFloat)layout:(WMELayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    if (_dataArr.count != 0) {
        //计算图片的高度
        //tw/th = iw/ih
        WMEFirstPageModel *m = _dataArr[indexPath.item];
        //图片高度
        CGFloat imgH = width * m.height.doubleValue / m.width.doubleValue;
        //文字高度
        //    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
        //    // 预设尺寸 文本最大不超过这个尺寸
        //    // 根据设置的宽度计算高度(宽度和label保持一致)
        //    CGSize size = CGSizeMake((414 - 30) /2, 1000);
        //    // 根据文本 计算出一个CGRect
        //    // 参数1: 尺寸范围
        //    // 参数2: 文本属性
        //    // 参数3: 按照什么方式获取rect
        //    // 参数4: nil
        //    CGRect rect = [m.msg boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        //    CGFloat h3 = rect.size.height;
        
        //文本高度
        CGFloat textHeight = [WMEFirstPageCollectionViewCell heightWithText:m.msg];
        //判断文本框 高度是否 超过 15.51 * 6 的 高度(6行的高度)
        if (textHeight >= 15.51 * 6) {
            //设置最大文本框行数 为 6行;
            textHeight = 15.51 * 6;
        }
        //    NSLog(@"%@      ======     %f  ~~~~ %f", m.msg, imgH, textHeight);
        // 每个cell的高度 由 图片高度 和 文本高度  + 其他控件高度(80)
        return imgH + textHeight + 80;
    }
    return 0;
}
#pragma maek - 加载
- (void)loadingFunction
{
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *url = [_urlStr stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%@", _nextStart]];
        //AFN网络请求
        AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
        [data GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //        NSLog(@"%@", responseObject);
            NSArray *arr = responseObject[@"data"][@"object_list"];
            self.nextStart = responseObject[@"data"][@"next_start"];
            // 把新请求来的数据 添加进 dataArr 数组
            NSArray *temp = [WMEFirstPageModel modelHandlerWithArray:arr];
            [_dataArr addObjectsFromArray:temp];
            [_collectionView reloadData];
            if (_nextStart.integerValue <= _dataArr.count) {
                [_collectionView.mj_footer endRefreshing];
            }else {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            nil;
        }];
    }];
}

#pragma mark -点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSLog(@"indexPath:%ld", (long)indexPath.row);
    //创建 对象
    WMEFirstPageInformationVC *information = [[WMEFirstPageInformationVC alloc] init];
    WMEFirstPageModel *m = _dataArr[indexPath.item];
    //把ID 传递给 下一页 的 接口
    information.jiekou = m.ID.stringValue;
    [self.navigationController pushViewController:information animated:YES];
    [information release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
